package com.example.springboot_practice.Config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Description: 测试配置多数据源
 * @Author 王宝凯
 * @Date 2020/9/9
 */
@Configuration
@MapperScan(value = "com.example.springboot_practice.Mapper.MapperOne",sqlSessionFactoryRef = "sqlSessionFactoryBeanTest1")
public class Test1MybatisConfig {

    @Autowired
    @Qualifier("TestOne")
    DataSource TestOne;

    @Bean
    SqlSessionFactory sqlSessionFactoryBeanTest1() throws Exception{
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(TestOne);
        //数据源是自己加载xml
        factoryBean.setMapperLocations(
                // 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
        return factoryBean.getObject();
    }
    @Bean
    SqlSessionTemplate sqlSessionTemplateTest1() throws Exception{
        return new SqlSessionTemplate(sqlSessionFactoryBeanTest1());
    }



    /*@Value("${Test1.datasource.url}")
    private String url;

    @Value("${Test1.datasource.username}")
    private String username;

    @Value("${Test1.datasource.password}")
    private String password;

    @Value("${Test1.datasource.driver-class-name}")
    private String driverClass;

    @Bean(name = "Test1DataSource")
    public DataSource Test1DataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "TestOneTransactionManager")
    public DataSourceTransactionManager TestOneTransactionManager(){
        return new DataSourceTransactionManager(Test1DataSource());
    }

    @Bean(name = "Test1SqlSessionFactory")
    public SqlSessionFactory Test1SqlSessionFactory() throws  Exception{
        final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(Test1DataSource());
        return sessionFactoryBean.getObject();
    }*/
}
